package com.csu.bailan.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csu.bailan.domain.AttrValue;
import com.csu.bailan.domain.Category;
import com.csu.bailan.domain.SKU;
import com.csu.bailan.domain.SPU;
import com.csu.bailan.dto.AddToCartDTO;
import com.csu.bailan.persistence.mapper.*;
import com.csu.bailan.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private SPUMapper spuMapper;
    @Autowired
    private SKUMapper skuMapper;
    @Autowired
    private AttributeMapper attributeMapper;
    @Autowired
    private AttrVMapper attrVMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<SPU> getSPUByCategory(String category) {
        // 未考虑类别的子类父类
        Category category1 = categoryMapper.selectOne(new QueryWrapper<Category>().eq("category", category));
        if (category1 != null)
            return spuMapper.selectList(new QueryWrapper<SPU>().eq("c_id", category1.getCId()));
        else return null;
    }

    @Override
    public List<SKU> getSKUListBySPUid(String spuId) {
        return skuMapper.selectList(new QueryWrapper<SKU>().eq("spu_id", spuId));
    }

    @Override
    public SKU getSKUBySKUid(String skuId) {
        return skuMapper.selectOne(new QueryWrapper<SKU>().eq("sku_id", skuId));
    }

    @Override
    public JSONObject getAttributesBySKUid(String skuId) {
        SKU sku = skuMapper.selectById(skuId);
        String attrStr = sku.getAttrId();
        JSONObject attrInDb = JSON.parseObject(attrStr);
        JSONObject attrJson = new JSONObject();
        for (String attrId : attrInDb.keySet()){
            String attrName = attributeMapper.selectById(attrId).getAttrName();
            String attrValue = attrVMapper.selectById(attrInDb.getString(attrId)).getAttrv();
            attrJson.put(attrName, attrValue);
        }
        return attrJson;
    }

    @Override
    public JSONArray getAttributesBySPUid(String spuId) {
        System.out.println("进入查询");
        SPU spu = spuMapper.selectById(spuId);
        if (spu == null){
            return null;
        }
        // SPU对应的所有SKU
        List<SKU> skus = skuMapper.selectList(new QueryWrapper<SKU>().eq("spu_id", spuId));
        System.out.println("查询结束");
        // 返回的SKU信息
        JSONArray skuInfos = new JSONArray();
        Set<String> attrSet = new HashSet<>();
        // 遍历SKU列表
        // 把所有的attr_id加入attr集合
        System.out.println("1");
        for (SKU s: skus) {
            if (s.getAttrId() != null){
                JSONObject atjson = JSON.parseObject(s.getAttrId());
                attrSet.addAll(atjson.keySet());
            }
        }
        System.out.println("2");
        if (attrSet.isEmpty()){
            System.out.println("SPU无属性");
            JSONObject joattr = new JSONObject();
            joattr.put("hasAttr", false);
            skuInfos.add(joattr);
            return skuInfos;
        }
        else {
            System.out.println("SPU有属性");
            JSONObject joattr = new JSONObject();
            joattr.put("hasAttr", true);
            skuInfos.add(joattr);
        }
        // 为每个属性创建一个容器以存放属性值
        JSONObject idjo = new JSONObject(true);
        for (String s: attrSet
             ) {
            idjo.put(s, new ArrayList<String>());
        }
        // 聚集信息
        for (SKU s: skus) {
            JSONObject atjson = JSON.parseObject(s.getAttrId());
            for (String attrId : atjson.keySet()){
                ArrayList<String> strings = (ArrayList<String>) idjo.get(attrId);
                AttrValue attrValue = attrVMapper.selectById(atjson.getString(attrId));
                String attrv = attrValue.getAttrvId()+":"+attrValue.getAttrv();
                strings.add(attrv);
                idjo.put(attrId, strings);
            }
        }
        // 遍历属性
        for (String attrId: idjo.keySet()
             ) {
            JSONObject jsonObject = new JSONObject(true);
            JSONObject atjo = new JSONObject();
            atjo.put("attr_id", attrId);
            atjo.put("attr_name", attributeMapper.selectById(attrId).getAttrName());
            jsonObject.put("attribute", atjo);
            jsonObject.put("attrValue", idjo.get(attrId));
            skuInfos.add(jsonObject);
        }
        return skuInfos;
    }

    @Override
    public boolean reduceSKUStock(String skuId) {
        SKU sku = skuMapper.selectById(skuId);
        if (sku.getStock() > 1){
            sku.setStock(sku.getStock()-1);
            return skuMapper.updateById(sku)==1;
        }
        return false;
    }

    @Override
    public SKU getSKUByAttrAndSPUid(String spuId, String attrId) {
        return skuMapper.selectOne(new QueryWrapper<SKU>().eq("spu_id", spuId).eq("attr_id", attrId));
    }

    @Override
    public boolean addToCart(AddToCartDTO dto) {
        return false;
    }

    @Override
    public List<SPU> selectPageByCID(String cid, int current, int page_num, double priceGt, double priceLt) {
        Page<SPU> spuiPage = new Page<>(current, page_num);
        if (priceGt == -1)
            priceGt = 0;
        if (priceLt == -1)
            priceLt = 9999999;
        spuiPage = spuMapper.selectPage(spuiPage, new QueryWrapper<SPU>().eq("c_id", cid).gt("avg_price", priceGt).lt("avg_price", priceLt));
        return spuiPage.getRecords();
    }

    @Override
    public List<SPU> selectPage(int current, int page_num, double priceGt, double priceLt) {
        IPage<SPU> spuiPage = new Page<>(current, page_num);
        if (priceGt == -1)
            priceGt = 0;
        if (priceLt == -1)
            priceLt = 9999999;
        spuiPage = spuMapper.selectPage(spuiPage, new QueryWrapper<SPU>().gt("avg_price", priceGt).lt("avg_price", priceLt));
        return spuiPage.getRecords();
    }
}
